﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TA.DotNetUtils
{
	public class PropertiesAccessor<T> : IPropertiesAccessor<T>
		where T : IPropertiesContainer
	{
		public virtual object GetValue(T t, string fieldName)
		{
			return this.GetValueInternal(t, fieldName);
		}

		private object GetValueInternal(IPropertiesContainer t, string fieldName)
		{
			if (fieldName.Contains("."))
			{
				string firstProp = fieldName.Substring(0, fieldName.IndexOf("."));
				string remainingProps = fieldName.Substring(fieldName.IndexOf(".") + 1);
				IPropertiesContainer next = (IPropertiesContainer)t.GetValue(firstProp);
				return this.GetValueInternal(next, remainingProps);
			}
			return t.GetValue(fieldName);
		}

		public virtual void SetValue(T t, string fieldName, object value)
		{
			t.SetValue(fieldName, value);
		}
	}
}
